#!/usr/bin/python
import sys,re,os, subprocess

def get_output(cmd):
    '''a little wrapper around subprocess.Popen'''
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    p.wait()
    if p.returncode != 0:
        raise 'subprocess returned: %d' % p.returncode
    return p.stdout

if len(sys.argv) > 2:
    print '%s [<tree-ish>]' % sys.argv[0]
    sys.exit(1)

if len(sys.argv) == 2:
    # the user supplied a tree-ish reference
    treeish = sys.argv[1]
else:
    # or we use the last svn merge point
    treeish = 'remotes/git-svn'

# find the svn rev of that treeish
svn_rev = get_output(['git-svn', 'find-rev', treeish]).read().strip()
if not len(svn_rev):
    print "I can't work out what SVN rev is associated with: %s" % treeish
    sys.exit(1)

# generate a diff and then fix it up to look like a svn diff
difflines = get_output(['cg', 'diff', '-r', treeish]).readlines()
for line in difflines:
    # match the first line
    m = re.match('^diff --git a/(?P<path>.*) b/(?P=path)\s*$', line)
    if m:
        sys.stdout.write('Index: %(path)s\n' % m.groupdict())
        continue

    # match the second line
    m = re.match('^index ', line)
    if m:
        sys.stdout.write(63*'=')
        sys.stdout.write('\n')
        continue

    # match the third line
    m = re.match('^--- a/(?P<path>.*)\s*$', line)
    if m:
        sys.stdout.write('--- %s\t(revision %s)\n' % 
                (m.groupdict()['path'], svn_rev))
        continue

    # match the fourth line
    m = re.match(r'^\+\+\+ b/(?P<path>.*)\s*$', line)
    if m:
        sys.stdout.write('+++ %s\t(working copy)\n' % m.groupdict()['path'])
        continue

    # pass everything else through
    sys.stdout.write(line)
